var http = require('http');
var url = require('url');
const { exit } = require('process');
var events = require('events');

// 创建 eventEmitter 对象
var eventEmitter = new events.EventEmitter();

// route 根路径
eventEmitter.on('/', function (method, response) {
  response.writeHead(200, { 'Content-Type': 'text/plain' });
  response.end('hello world');
});

eventEmitter.on('/normalError', function (method, response) {
  response.writeHead(200, { 'Content-Type': 'application/json' });
  response.end(
    JSON.stringify({
      code: 4000,
      message: '用户名重复',
    }),
  );
});

eventEmitter.on('/getLoginUser', function (method, response) {
  response.writeHead(200, { 'Content-Type': 'application/json' });
  response.end(
    JSON.stringify({
      code: 777,
      message: 'token过期，请重新登录',
    }),
  );
});

eventEmitter.on('/serviceError', function (method, response) {
  response.writeHead(500, { 'Content-Type': 'application/json' });
  response.end(
    JSON.stringify({
      code: 4000,
      message: '用户名重复',
    }),
  );
});

// route
eventEmitter.on('/list', function (method, response) {
  const list = [];
  for (let index = 0; index < 100; index++) {
    const element = {
      id: index,
      name: '小明',
      account: 'Y12',
      phone: 111,
      status: 1,
    };
    list.push(element);
  }
  response.writeHead(200, { 'Content-Type': 'application/json' });
  response.end(
    JSON.stringify({
      code: 0,
      data: {
        page: 1,
        totalCount: 100,
        list,
      },
    }),
  );
});

// 启动服务
http
  .createServer(function (request, response) {
    console.log(request.url);

    // 分发
    if (eventEmitter.listenerCount(request.url) > 0) {
      eventEmitter.emit(request.url, request.method, response);
    } else {
      eventEmitter.emit('404', request.method, request.url, response);
    }
  })
  .listen(8888);

console.log('Server running at http://127.0.0.1:8888/');
